<template>
  <div
    ref="propertyTable"
    class="v-property-table g-relative"
  >
    <div class="_table-body">
      <div class="g-relative g-pd-l-10 g-pd-b-1">
        <div
          v-for="(group, idx) of tableDataGroups"
          :key="(group.instanceId || '0') + group.key"
        >
          <div
            class="g-flex _table-row g-ov-hidden _table-title"
            :class="{
              '_table-title-has-no-border-top': tableDataGroups[idx - 1] && tableDataGroups[idx - 1].expand,
              '_table-title-has-border-bottom': idx === tableDataGroups.length - 1 && !group.expand
            }"
          >
            <div class="g-flex-0 _name-column g-one-line g-bolder">
              <div
                class="g-inline-block g-pointer"
                @click="toggleGroupExpand(idx)"
              >
                <img
                  v-show="!group.expand"
                  src="statics/icons/app/iconadd.svg"
                  alt=""
                />
                <img
                  v-show="group.expand"
                  src="statics/icons/app/iconreduce.svg"
                  alt=""
                />
              </div>
              <template v-if="idx === 0">
                {{ group.model?.modelTypeCnName && $t(group.model.modelTypeCnName) }}
              </template>
              <template v-else>
                {{ locale.getTByKey(`propertyConfig.${group.key}`, group.name) }}
                {{ group.model?.name ? "( " + group.model.name + " )" : "" }}
              </template>
            </div>
          </div>
          <template v-if="group.expand">
            <div
              v-for="(row, index) of group.properties"
              :id="`propertyTable_${row.key}`"
              :key="row.key"
              class="g-flex _table-row g-ov-hidden"
              :class="{ '_current-row': isRowSelected(row) }"
              @click="handleClickRow(row)"
            >
              <div
                v-show="isRowSelected(row)"
                class="_table-body-icon"
              >
                <img src="statics/icons/app/arrowchoose.svg" />
              </div>
              <div
                class="g-flex-0 _cell _name-column g-one-line"
                :style="{ width: nameColumnWidth + 'px' }"
                @contextmenu="handleContextMenu(row, $event)"
              >
                <span>
                  {{ locale.getTByKey(`propertyConfig.${row.key}`, row.name) }}
                </span>
                <el-icon
                  v-show="isShowComment"
                  v-if="(row.priorityCommentLevel ?? -1) > -1"
                  :size="14"
                  :color="isRowSelected(row) ? '#ffff' : commentColors?.[row?.priorityCommentLevel ?? 1]"
                >
                  <Marking :circleColor="isRowSelected(row) ? '#3F9EFF' : undefined" />
                </el-icon>
              </div>
              <div class="g-flex-1 _cell _value-column">
                <div
                  v-if="row.modelIds?.length && !isRowSelected(row) && !row.consistent"
                  class="g-m-l-4"
                >
                  {{ $t("<多个值>") }}
                </div>
                <component
                  :is="propertyManager.getEditorByPropertyRow(row)"
                  v-else
                  :key="row.key"
                  :class="{ _disabled: row.readonly }"
                  :row="row"
                  :encrypted="encrypted"
                  :selected="isRowSelected(row)"
                  :isShowTerm="row.key === PropertyKey.NamedElement_name ? true : false"
                />
              </div>
            </div>
          </template>
        </div>
        <!-- <SlotTable
          v-if="attributeTabsModel.data.modelData?.id && attributeTabsModel.data.projectId"
          :key="attributeTabsModel.data.modelData.id"
          :slotData="attributeTabsModel.propertyPaneModel.classifierSlotsData"
          :modelId="attributeTabsModel.data.modelData.id"
          :projectId="attributeTabsModel.data.projectId"
          :nameColumnWidth="nameColumnWidth"
          :activeRowId="activeRowId"
          :slotsPaneModel="attributeTabsModel.slotPaneModel"
          @handleCilckRow="handleClickRow"
        /> -->
        <span
          class="_movebar _vertical g-block"
          :style="{ left: nameColumnWidth - 4 + 'px' }"
          @mousedown="handleMouseDownVertical"
        ></span>
      </div>
    </div>
    <div
      v-if="showTips"
      class="_tips"
    >
      <span
        v-if="currentRow?.name"
        class="_footer-name"
      >
        {{ currentRow.displayName }}:
      </span>
      <span
        v-if="tipText"
        class="_footer-tips"
      >
        {{ tipText }}
      </span>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, reactive, watchEffect, watch } from "vue";
import { propertyManager } from "./PropertyManager";
import { PropertyRow, PropertyRowGroup } from "./types";
import { locale } from "@/util/locale";
import SlotTable from "./SlotTable.vue";
import { modelService } from "@/modules/model/service";
import { PropertyKey } from "@/constants/Enums";
import { commentColors } from "@/constants/constants";
import Marking from "@/common/icons/Marking.vue";
import ContextMenu from "@/common/ContextMenu/index.vue";
import { propertyUtil } from "./PropertyUtil";
import { actionManager } from "@/action/ActionManager";
import type { AttributeTabsModel } from "./models/AttributeTabsModel";

const attributeTabsModel = app.activeProject!.attributeTabsModel as AttributeTabsModel;

const props = defineProps<{
  tableDataGroups: PropertyRowGroup[];
  showTips?: boolean;
  instanceName?: string;
  encrypted?: boolean;
  isShowComment?: boolean;
  activeRowId?: string;
  // activeProperty:string
}>();

// const emit = defineEmits<{
//   (e:'update:activeProperty', data:string):void
// }>();

// const currentKey = computed<string>({
//   get: () => props.activeProperty,
//   set: (val) => emit('update:activeProperty', val)
// });

// const activeProperty = computed(() => {
//   return app.activeProject?.attributeTabsModel.data.activeProperty;
// });

function getPropertyPaneModel() {
  return app.activeProject?.attributeTabsModel.propertyPaneModel;
}

function isRowSelected(row: PropertyRow) {
  if (!props.activeRowId) {
    return false;
  }
  return row.id_ === props.activeRowId; // && row.key === data.activeProperty;
}
// const propertyPaneModel = computed(() => {
//   return getPropertyPaneModel()!;

// });
// 初始化清空 currentKey

if (app.activeProject?.attributeTabsModel.propertyPaneModel) {
  app.activeProject.attributeTabsModel.propertyPaneModel.activeRowId = undefined;
}
// currentKey.value = '';

const propertyTable = ref(null);
const nameColumnWidth = ref<number>(110);
let mouseStartX = 0;
let originWidth = 0;
const minWidth = 20;
const expand = ref(true);

const tips = reactive({ en: "", cn: "" });

// const currentRow = computed(() => {
//   if (!props.activeRowId) {
//     return undefined;
//   }

//   for (const group of props.tableDataGroups) {
//     for (const row of group.properties) {
//       if (row.id_ === props.activeRowId) {
//         return row;
//       }
//     }
//   }
//   return undefined;
//   // return props.tableData.find(item => item.key === props.activeProperty);
// });

const currentRow = ref();

watch(
  () => props.activeRowId,
  newValue => {
    currentRow.value = undefined;

    if (newValue) {
      for (const group of props.tableDataGroups) {
        for (const row of group.properties) {
          if (row.id_ === newValue) {
            currentRow.value = row;
          }
        }
      }
    }
  }
);

const tipText = computed(() => {
  return locale.value === "en" ? tips.en : tips.cn;
});

function handleClickRow(row: PropertyRow) {
  console.log("property---", row);
  app.activeProject!.attributeTabsModel.propertyPaneModel.activeRowId = row.id_;
  // currentKey.value = row.key;
  // emit('handleTips', row.tips);
}

watch(
  () => props.tableDataGroups,
  newValue => {
    if (!currentRow.value) {
      if (!newValue[0]) return;
      app.activeProject!.attributeTabsModel.propertyPaneModel.activeRowId = props.tableDataGroups[0]?.properties[0]?.id_;

      // currentKey.value = newValue[0].key;
    }
  }
);
function handleMouseDownVertical(event: any) {
  mouseStartX = event.clientX;
  originWidth = nameColumnWidth.value;
  window.addEventListener("mousemove", handleMouseMoveVertical);
  window.addEventListener("mouseup", handleMouseUpVertical);
}

function handleMouseMoveVertical(event: any) {
  const maxWidth = app.global.siderWidth - 40;
  const mouseEndX = event.clientX;
  let changeWidth = mouseEndX - mouseStartX;
  let width = originWidth + changeWidth;
  if (width > maxWidth) {
    width = maxWidth;
  } else if (width < minWidth) {
    width = minWidth;
  }
  nameColumnWidth.value = width;
}

function handleMouseUpVertical() {
  window.removeEventListener("mousemove", handleMouseMoveVertical);
  window.removeEventListener("mouseup", handleMouseUpVertical);
}
async function handleContextMenu(propertyRow: PropertyRow, event: MouseEvent) {
  event.preventDefault();
  const project = app.activeProject;
  if (!project) return;
  let menus = await propertyUtil.getPropertyContextMenu(propertyRow);
  if (!menus?.length) return;
  ContextMenu.popup({
    x: event.clientX,
    y: event.clientY,
    menuItems: menus
  })
    .then(menuItem => {
      const action = actionManager.getAction(menuItem.value);
      if (!action) return;
      action.ontPropertyMenuClick?.(propertyRow);
    })
    .catch((e: Error) => {
      e && console.error(e);
    });
}

watchEffect(() => {
  if (props.showTips) {
    loadTips();
  } else {
    clearTips();
  }
});
async function loadTips() {
  if (currentRow.value) {
    const modelId = app.activeProject?.attributeTabsModel.modelId;
    const modelIds = app.activeProject?.attributeTabsModel.data.modelIds || [];
    const projectId = app.activeProject?.id;
    if ((!modelId && !modelIds.length) || !projectId) {
      clearTips();
      return;
    }
    const resData = await modelService.getPropertyTips(app.activeProject.id, currentRow.value.key);
    tips.en = resData.enTips;
    tips.cn = resData.tips;
  } else {
    clearTips();
  }
}

function toggleGroupExpand(index: number) {
  const group = app.activeProject?.attributeTabsModel.propertyPaneModel?.tableDataGroups[index];
  if (group) {
    group.expand = !group.expand;
  }
}

function clearTips() {
  tips.en = "";
  tips.cn = "";
}
</script>
<style lang="scss">
@import "@/assets/css/theme.scss";

.v-property-table {
  height: 100%;
  overflow: hidden;
  display: flex;
  .v-collapse {
    position: absolute;
    left: -13px;
    top: 7px;
    cursor: pointer;
    vertical-align: middle;
    font-size: 0;
  }
  ._table-body-icon {
    position: absolute;
    left: 2px;
    margin-top: 4px;
  }

  flex-direction: column;

  ._table-body {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    ._table-row:nth-of-type(odd) {
      background: $nth-of-type-bg-color;

      .el-input__wrapper {
        background: $nth-of-type-bg-color;
      }
    }

    ._table-row:nth-of-type(even) {
      background: #fff;
    }
  }
  ._table_group {
    border-bottom: 1px solid #ddd;
  }
  ._table-title {
    border-top: 1px solid $btn-border-color;
    border-left: 1px solid $btn-border-color;
    border-right: 1px solid $btn-border-color;
    box-sizing: border-box;
    font-size: 12px;
    line-height: 28px;

    img {
      position: relative;
      top: -1px;
    }
  }
  ._table-title-has-no-border-top {
    border-top: 0;
  }
  ._table-title-has-border-bottom {
    border-bottom: 1px solid $btn-border-color;
  }

  ._tips {
    flex: 0 0 auto;
    font-size: 12px;
    height: 64px;
    padding: 8px 10px;
    background: var(--md-color-sub3);
    overflow: auto;
    margin-left: 10px;

    ._footer-name {
      line-height: 16px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.85);
    }

    ._footer-tips {
      font-size: 12px;
      line-height: 16px;
      word-break: break-all;
      overflow: auto;
    }
  }

  ._cell {
    border-top: 1px solid $btn-border-color;
    border-left: 1px solid $btn-border-color;
    box-sizing: border-box;
    font-size: 11px;
    line-height: 24px;
  }

  ._name-column {
    padding: 0 8px;
    display: flex;
    align-items: center;
    gap: 5px;

    //超出省略号
    span {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  ._value-column {
    padding: 0;
    line-height: 24px;
    // overflow-x: hidden;
    border-right: 1px solid $btn-border-color;
  }

  ._current-row {
    ._cell {
      border-top-color: $theme-color;
      border-left-color: $theme-color;
    }

    ._name-column {
      padding: 0 8px;

      background: $theme-color;
      color: white;
    }

    ._value-column {
      box-sizing: border-box;
      line-height: 24px;
      border-right-color: $theme-color;
    }
  }

  ._current-row + ._table-row {
    line-height: 24px;

    ._cell {
      border-top-color: $theme-color;
    }
  }

  ._table-row:last-of-type {
    min-height: 28px;
    ._cell {
      border-bottom: 1px solid $btn-border-color;
      line-height: 26px;
    }
  }

  ._table-row._current-row:last-of-type {
    ._cell {
      border-bottom: 1px solid $theme-color;
    }
  }

  .el-input__inner {
    border: none;
    box-sizing: border-box;
    height: 24px;
    line-height: 24px;
    background: none;
    box-shadow: none;
    text-align: left;
  }

  .el-textarea__inner:focus {
    background: none;
    box-shadow: none;
  }

  .el-textarea__inner {
    background: none;
    box-shadow: none;
    padding: 0px 2px;
    border: none;
    overflow: auto;
    text-overflow: ellipsis;
  }

  .el-input-border {
    border: none;
  }

  ._disabled {
    cursor: not-allowed;
  }

  ._movebar {
    position: absolute;

    &._vertical {
      cursor: col-resize;
      width: 8px;
      height: 100%;
      top: 0;
    }
  }
}
</style>
